﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Web.Helpers
{
    public class WebHelper : System.Web.UI.Page
    {
        public static HttpContext GetCurrentContext()
        {
            return HttpContext.Current;
        }

        public class Pages
        {
            public static string GetPageName()
            {
                //Method 1: return System.IO.Path.GetFileName(request.PhysicalPath);
                //Method 2: return System.IO.Path.GetFileNameWithoutExtension(request.Path);
                //Method 3: return new System.IO.FileInfo(request.Url.AbsolutePath).Name; 
                var request = GetCurrentContext().Request;
                return System.IO.Path.GetFileName(request.Path);
            }     
       
            public class QueryString
            {
                public static Dictionary<string, string> GetAllParameters()
                {
                    var parameters = new Dictionary<string, string>();
                    try
                    {
                        var queryString = GetCurrentContext().Request.QueryString;
                        foreach (var key in queryString.AllKeys)
                        {
                            parameters.Add(key, queryString[key]);
                        }
                    }
                    catch (Exception)
                    {
                        //throw;
                    }
                    return parameters;
                }

                public static string GetParameter(string name)
                {
                    return GetParameter<string>(name);
                }
                public static T GetParameter<T>(string name)
                {
                    var value = default(T);
                    object valueFound = null;
                    try
                    {
                        var queryString = GetCurrentContext().Request.QueryString;
                        //value = queryString[name];
                        if ( queryString.Count > 0 )
                        {
                            var values = queryString.GetValues(name);
                            if (values != null && values.Length > 0)
                                valueFound = values.First();
                        }
                        //if ( valueFound != null )
                        //    value = (T)valueFound;
                        if ( valueFound != null )
                            value = (T)Convert.ChangeType(valueFound, typeof(T));
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    return value;
                }
            }
        }

        public new class Session
        {
            public static T Get<T>(string key, HttpContext context = null)
            {
                try
                {
                    var currentContext = context ?? GetCurrentContext();
                    return (T)currentContext.Session[key];
                }
                catch (Exception)
                {
                    //throw;
                }
                return default(T);
            }
            public static void Set(string key, object value, HttpContext context = null)
            {
                var currentContext = context ?? GetCurrentContext();
                currentContext.Session[key] = value;
            }
            public static bool RemoveValue(string key, HttpContext context = null)
            {
                var removed = false;
                try
                {
                    if (key.IsNotNull() && key.Length > 0)
                    {
                        var currentContext = context ?? GetCurrentContext();
                        if (currentContext.Session[key] != null)
                            currentContext.Session.Remove(key);
                        removed = true;
                    }
                }
                catch (Exception)
                {
                    // throw;
                }
                return removed;
            }
        }

        public class Cache
        {
            public static T GetValue<T>(string key, HttpContext context = null)
            {
                try
                {
                    var currentContext = context ?? GetCurrentContext();
                    if ( key.IsNotNull() )
                        return (T)currentContext.Cache[key];
                    else
                        return default(T);
                }
                catch (Exception)
                {
                    throw;
                }
            }

            public static void SetValue<T>(string key, T value, HttpContext context = null)
            {
                try
                {
                    if ( value.IsNull() || key.IsNull() )
                        return;

                    var currentContext = context ?? GetCurrentContext();
                    if ( GetValue<T>(key).IsNull() )
                        currentContext.Cache.Add(key, value, null, DateTime.Now.AddMonths(1), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
                    else
                        currentContext.Cache[key] = value;
                }
                catch (Exception)
                {
                    throw;
                }
            }

            public static void RemoveValue(string key, HttpContext context = null)
            {
                try
                {
                    if ( key.IsNotNull() && key.Length > 0 )
                    {
                        var currentContext = context ?? GetCurrentContext();
                        if (currentContext.Cache[key] != null)
                        currentContext.Cache.Remove(key);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }

        /// <summary>
        /// Streams the content of a file to the browser for download.
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="fileBytes"></param>
        public static void StreamFileToBrowser(string fileName, byte[] fileBytes)
        {
            var context = HttpContext.Current;
            context.Response.Clear();
            context.Response.ClearHeaders();
            context.Response.ClearContent();
            context.Response.BufferOutput = false; // for large files
            context.Response.AppendHeader("content-length", fileBytes.Length.ToString());
            context.Response.ContentType = "application/octet-stream"; //GetMimeTypeByFileName(fileName);
            context.Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
            context.Response.BinaryWrite(fileBytes);

            // use this instead of response.end to avoid thread aborted exception (known issue):
            // http://support.microsoft.com/kb/312629/EN-US
            context.ApplicationInstance.CompleteRequest();
        }

        /// <summary>
        /// Gets the MIME type of the file name specified based on the file name's
        /// extension.  If the file's extension is unknown, returns "octet-stream"
        /// generic for streaming file bytes.
        /// </summary>
        /// <param name="sFileName">The name of the file for which the MIME type
        /// refers to.</param>
        public static string GetMimeTypeByFileName(string sFileName)
        {
            var sMime = "application/octet-stream";
            var sExtension = System.IO.Path.GetExtension(sFileName);
            if (!string.IsNullOrEmpty(sExtension))
            {
                sExtension = sExtension.Replace(".", "");
                sExtension = sExtension.ToLower();
                if (sExtension == "xls" || sExtension == "xlsx")
                {
                    sMime = "application/ms-excel";
                }
                else if (sExtension == "doc" || sExtension == "docx")
                {
                    sMime = "application/msword";
                }
                else if (sExtension == "ppt" || sExtension == "pptx")
                {
                    sMime = "application/ms-powerpoint";
                }
                else if (sExtension == "rtf")
                {
                    sMime = "application/rtf";
                }
                else if (sExtension == "zip")
                {
                    sMime = "application/zip";
                }
                else if (sExtension == "mp3")
                {
                    sMime = "audio/mpeg";
                }
                else if (sExtension == "bmp")
                {
                    sMime = "image/bmp";
                }
                else if (sExtension == "gif")
                {
                    sMime = "image/gif";
                }
                else if (sExtension == "jpg" || sExtension == "jpeg")
                {
                    sMime = "image/jpeg";
                }
                else if (sExtension == "png")
                {
                    sMime = "image/png";
                }
                else if (sExtension == "tiff" || sExtension == "tif")
                {
                    sMime = "image/tiff";
                }
                else if (sExtension == "txt")
                {
                    sMime = "text/plain";
                }
            }
            return sMime;
        }
    }
}